<template>
  <div class="user-avatar">
    <img :src="uploadStore.imgurl || defaultAvatarUrl" alt="" class="avatar" />
    <el-form label-width="100px">
      <el-upload
        class="user-avatar_el_upload"
        :limit="1"
        list-type="picture-card"
        :on-change="handleChange"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :on-error="handleError"
        :file-list="uploadStore.fileList"
        :class="{ disUoloadSty: uploadStore.uploadDisabled }"
        ref="uploadRef"
      >
        <span class="user-avatar_el_upload_btn" @click.stop="submitUpload"
          >上传头像</span
        >
      </el-upload>
    </el-form>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { useUploadStore } from "../stores/user";
import { ElMessage } from "element-plus";
import { uploadAvatarService } from "../api/user";

const uploadStore = useUploadStore();
const cUserAvatar = ref(""); // 从 props 接收
const defaultAvatarUrl = "/default-avatar-path"; // 设置默认头像路径
const uploadRef = ref(null); // 用于引用 el-upload 组件

const handleError = (err, file, fileList) => {
  ElMessage({
    message: "上传失败！",
    type: "error",
  });
  console.log(err);
};

const handleSuccess = (response, file, fileList) => {
  if (response.flag) {
    uploadStore.addFile(file);
    cUserAvatar.value = response.data;
    updateAvatar(response.data); // 调用更新头像的方法
    alert(response.message);
  } else {
    alert(response.data);
  }
};

const handleChange = (file, fileList) => {
  uploadStore.fileList = fileList;
};

const handleRemove = (file, fileList) => {
  uploadStore.removeFile();
};

const handlePreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};

const submitUpload = () => {
  uploadRef.value.submit(); // 使用 uploadRef 提交上传
};

// 上传成功后更新头像
const updateAvatar = async (avatarUrl) => {
  try {
    const response = await uploadAvatarService(avatarUrl);
    if (response.flag) {
      uploadStore.updateImgUrl(response.data);
      // 这里可以进一步更新用户信息，例如更新 Pinia store 中的用户头像信息
    } else {
      alert(response.data);
    }
  } catch (err) {
    alert(err.message);
  }
};
</script>

<style lang="less" scoped>
.disUoloadSty .el-upload--picture-card {
  display: none; /* 上传按钮隐藏 */
}
.user-avatar {
  width: 1200px;
  height: 150px;
  .avatar {
    float: left;
    width: 148px;
    height: 148px;
    border-radius: 50%;
  }
  .user-avatar_el_upload {
    width: 1000px;
    float: left;
    height: 148px;
    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      &:hover {
        border-color: #409eff;
      }
      .el-upload__input {
        position: absolute;
        left: -1000px;
      }
    }
  }
}
</style>